package com.imooc.service.impl.center;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.ItemsCommentsMapperCustom;
import com.imooc.mapper.OrderItemsMapper;
import com.imooc.mapper.OrderStatusMapper;
import com.imooc.mapper.OrdersMapper;
import com.imooc.pojo.OrderItems;
import com.imooc.pojo.OrderStatus;
import com.imooc.pojo.Orders;
import com.imooc.pojo.bo.center.OrderItemsCommentBO;
import com.imooc.pojo.vo.MyCommentVO;
import com.imooc.service.center.MyCommentsService;
import com.imooc.utils.PagedGridResult;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
public class MyCommentsServiceImpl extends BaseService implements MyCommentsService {

  private final OrderItemsMapper orderItemsMapper;

  private final OrdersMapper ordersMapper;

  private final OrderStatusMapper orderStatusMapper;

  private final ItemsCommentsMapperCustom itemsCommentsMapperCustom;

  private final Sid sid;

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
  @Override
  public List<OrderItems> queryPendingComment(String orderId) {
    return orderItemsMapper
        .selectList(Wrappers.<OrderItems>lambdaQuery().eq(OrderItems::getOrderId, orderId));
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
  @Override
  public void saveComments(String orderId, String userId,
      List<OrderItemsCommentBO> commentList) {
    // 1. 保存评价 items_comments
    for (OrderItemsCommentBO oic : commentList) {
      oic.setCommentId(sid.nextShort());
    }
    Map<String, Object> map = new HashMap<>();
    map.put("userId", userId);
    map.put("commentList", commentList);
    itemsCommentsMapperCustom.saveComments(map);
    // 2. 修改订单表改已评价 orders
    Orders order = new Orders();
    order.setId(orderId);
    order.setIsComment(YesOrNo.YES.type);
    ordersMapper.updateById(order);
    // 3. 修改订单状态表的留言时间 order_status
    OrderStatus orderStatus = new OrderStatus();
    orderStatus.setOrderId(orderId);
    orderStatus.setCommentTime(new Date());
    orderStatusMapper.updateById(orderStatus);
  }

  @Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
  @Override
  public PagedGridResult queryMyComments(String userId,
      Integer page,
      Integer pageSize) {
    Map<String, Object> map = new HashMap<>();
    map.put("userId", userId);
    PageHelper.startPage(page, pageSize);
    List<MyCommentVO> list = itemsCommentsMapperCustom.queryMyComments(map);
    return setterPagedGrid(list, page);
  }
}
